<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>闭包</title>
    <script type="text/javascript">
        window.onload = function (){
            let btns = document.getElementsByTagName('button');
            // for (let i = 0,length = btns.length; i < length; i++) {
            //     let btnIndex = i;
            //     btns[i].onclick = function (){
            //         alert(btnIndex+1);
            //     }
            // }

            //利用闭包
            for (let i = 0,length = btns.length; i < length; i++) {
                (function (i){
                    btns[i].onclick = function () {
                        alert(i+1);
                    }
                })(i);
            }
        }
    </script>
</head>
<body>
<div>
    <button id="1">1</button>
    <button id="2">2</button>
    <button id="3">3</button>
</div>
</body>
</html>